package com.hrm.service.impl;

import com.hrm.mapper.UsersMapper;
import com.hrm.pojo.Users;
import com.hrm.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class UsersServiceImpl implements UsersService{

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 注册
     * @param users
     * @return
     * @throws Exception
     */
    @Override
    public boolean register(Users users) throws Exception {
        //险些用户密码进行加密
        String newPwd=bCryptPasswordEncoder.encode(users.getPassword());
        System.out.println("加密后的密码："+newPwd);
        //设置加密后的密码
        users.setPassword(newPwd);
        if (usersMapper.insertSelective(users)>0){
            return true;
        }
        return false;
    }

    /**
     * 登录
     * @param loginname
     * @param pwd
     * @return
     * @throws Exception
     */
    @Override
    public Users login(String loginname, String pwd) throws Exception {
        //1.根据用户名查找用户信息
        Users users = usersMapper.selectByLoginName(loginname);
        if (users==null){
            throw new Exception("用户名不存在");
        }
        //2.根据查找到的用户的密码和输入的密码进行校验,pwd是加密前的，users.getPassword()是从数据库获取的加密后的密码
        boolean flag = bCryptPasswordEncoder.matches(pwd, users.getPassword());
        if (!flag){
            throw new Exception("密码不正确");
        }
        return users;
    }
}
